package mylab.base.foundation.orm.ability;

import com.google.common.collect.Lists;

import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import cn.hutool.db.Entity;
import mylab.base.foundation.lang.Identifiable;
import mylab.base.foundation.orm.EntityUtil;

public interface Insert<T extends Identifiable<Long>> extends DS, EntityInfo<T> {
    default Long insert(T entity) throws SQLException {
        return getDb().insertForGeneratedKey(EntityUtil.fromBean(entity));
    }

    default Long insert(Map<String, Object> map) throws SQLException {
        Entity entity = Entity.create(getTableName());
        entity.putAll(map);
        return insert(entity);
    }

    default Long insert(Entity entity) throws SQLException {
        return getDb().insertForGeneratedKey(entity);
    }

    default Long[] insertBatch(Collection<T> entities) throws SQLException {
        List<T> list = Lists.newArrayList(entities);
        Long[] ids = new Long[list.size()];
        DsAdmin.tx(getDb(), db -> {
            try {
                for (int i = 0; i < list.size(); i++) {
                    ids[i] = getDb().insertForGeneratedKey(EntityUtil.fromBean(list.get(i)));
                }
            } catch (SQLException e) {
                return e;
            }
            return null;
        });

        return ids;
    }
}
